import { NextResponse } from 'next/server';
import { sqliteDb } from '@/lib/sqlite-database';

export async function POST() {
  try {
    const testDeviceId = `TEST-${Date.now()}`;
    const testData = {
      device_id: testDeviceId,
      name: "中文测试设备",
      classification_name: "中文测试分类",
      classification_code: "TEST-CN",
      specialty: "配管专业",
      naming_table_id: "C2",
      position_table_id: "C4",
      base_params_table_id: "C18",
      tech_spec_table_id: "-",
      sequence_number: "999",
      remarks: "中文字符编码测试：测试中文保存和读取功能是否正常"
    };

    // 插入测试设备
    const insertedDevice = sqliteDb.insertDevice(testData);
    
    // 立即读取回来检查
    const retrievedDevice = sqliteDb.getDeviceByDeviceId(testDeviceId);
    
    if (!retrievedDevice) {
      throw new Error('测试设备插入后无法找到');
    }

    // 检查中文字符是否正确保存
    const isChineseCorrect = 
      retrievedDevice.name === testData.name &&
      retrievedDevice.classification_name === testData.classification_name &&
      retrievedDevice.specialty === testData.specialty &&
      retrievedDevice.remarks === testData.remarks;

    if (!isChineseCorrect) {
      return NextResponse.json({
        success: false,
        message: `中文字符保存异常！\n期望：${testData.name}\n实际：${retrievedDevice.name}`,
        originalData: testData,
        retrievedData: retrievedDevice
      });
    }

    return NextResponse.json({
      success: true,
      message: '中文字符保存和读取测试通过！',
      deviceId: testDeviceId,
      testData: retrievedDevice
    });

  } catch (error) {
    console.error('中文字符测试失败:', error);
    return NextResponse.json({
      success: false,
      message: `测试失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  }
} 